import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../serve/docx_reader_service.dart';

/// DOCX文件查看器组件
class DocxViewerWidget extends StatefulWidget {
  final String filePath;
  final String? title;
  final bool showFileInfo;
  final bool enableSearch;

  const DocxViewerWidget({
    Key? key,
    required this.filePath,
    this.title,
    this.showFileInfo = true,
    this.enableSearch = true,
  }) : super(key: key);

  @override
  _DocxViewerWidgetState createState() => _DocxViewerWidgetState();
}

class _DocxViewerWidgetState extends State<DocxViewerWidget> {
  final DocxReaderService _docxReader = DocxReaderService();
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  DocxContent? _docxContent;
  List<SearchResult> _searchResults = [];
  bool _isLoading = true;
  String? _errorMessage;
  bool _isSearching = false;
  int _currentSearchIndex = -1;

  @override
  void initState() {
    super.initState();
    _loadDocxContent();
  }

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _loadDocxContent() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      final content = await _docxReader.readDocxFile(widget.filePath);
      
      setState(() {
        _docxContent = content;
        _isLoading = false;
      });

    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  Future<void> _performSearch(String keyword) async {
    if (keyword.isEmpty) {
      setState(() {
        _searchResults = [];
        _currentSearchIndex = -1;
      });
      return;
    }

    setState(() {
      _isSearching = true;
    });

    try {
      final results = await _docxReader.searchInDocx(widget.filePath, keyword);
      setState(() {
        _searchResults = results;
        _currentSearchIndex = results.isNotEmpty ? 0 : -1;
        _isSearching = false;
      });

      if (results.isNotEmpty) {
        _showSearchResultSnackBar(results.length);
      }

    } catch (e) {
      setState(() {
        _isSearching = false;
        _searchResults = [];
        _currentSearchIndex = -1;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('搜索失败: $e')),
      );
    }
  }

  void _showSearchResultSnackBar(int count) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('找到 $count 个匹配项'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  void _navigateSearchResult(bool next) {
    if (_searchResults.isEmpty) return;

    setState(() {
      if (next) {
        _currentSearchIndex = (_currentSearchIndex + 1) % _searchResults.length;
      } else {
        _currentSearchIndex = (_currentSearchIndex - 1 + _searchResults.length) % _searchResults.length;
      }
    });
  }

  void _copyContent() {
    if (_docxContent != null) {
      Clipboard.setData(ClipboardData(text: _docxContent!.content));
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('内容已复制到剪贴板')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        if (widget.enableSearch) _buildSearchBar(),
        if (widget.showFileInfo && _docxContent != null) _buildFileInfo(),
        Expanded(child: _buildContent()),
      ],
    );
  }

  Widget _buildSearchBar() {
    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: '搜索文档内容...',
                prefixIcon: Icon(Icons.search),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              onSubmitted: _performSearch,
            ),
          ),
          SizedBox(width: 8),
          if (_isSearching)
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 2),
            )
          else
            IconButton(
              icon: Icon(Icons.search),
              onPressed: () => _performSearch(_searchController.text),
            ),
          if (_searchResults.isNotEmpty) ...[
            IconButton(
              icon: Icon(Icons.keyboard_arrow_up),
              onPressed: () => _navigateSearchResult(false),
            ),
            IconButton(
              icon: Icon(Icons.keyboard_arrow_down),
              onPressed: () => _navigateSearchResult(true),
            ),
            Text(
              '${_currentSearchIndex + 1}/${_searchResults.length}',
              style: TextStyle(fontSize: 12, color: Colors.grey[600]),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildFileInfo() {
    final content = _docxContent!;
    
    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.blue[50],
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.description, color: Colors.blue[700]),
              SizedBox(width: 8),
              Expanded(
                child: Text(
                  widget.title ?? content.fileName,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue[700],
                  ),
                ),
              ),
              IconButton(
                icon: Icon(Icons.copy),
                onPressed: _copyContent,
                tooltip: '复制全部内容',
              ),
            ],
          ),
          SizedBox(height: 8),
          Row(
            children: [
              _buildInfoChip('大小', content.formattedFileSize),
              SizedBox(width: 8),
              _buildInfoChip('字数', '${content.wordCount}'),
              SizedBox(width: 8),
              _buildInfoChip('段落', '${content.paragraphCount}'),
            ],
          ),
          SizedBox(height: 4),
          Text(
            '修改时间: ${content.formattedLastModified}',
            style: TextStyle(fontSize: 12, color: Colors.grey[600]),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoChip(String label, String value) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[300]!),
      ),
      child: Text(
        '$label: $value',
        style: TextStyle(fontSize: 12, color: Colors.grey[700]),
      ),
    );
  }

  Widget _buildContent() {
    if (_isLoading) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('正在读取DOCX文件...'),
          ],
        ),
      );
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.red[300]),
            SizedBox(height: 16),
            Text(
              '读取失败',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Text(
              _errorMessage!,
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.grey[600]),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadDocxContent,
              child: Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_docxContent == null) {
      return Center(child: Text('无内容'));
    }

    return Container(
      padding: EdgeInsets.all(16),
      child: SingleChildScrollView(
        controller: _scrollController,
        child: _buildFormattedContent(),
      ),
    );
  }

  Widget _buildFormattedContent() {
    final content = _docxContent!.content;
    final searchKeyword = _searchController.text;

    if (searchKeyword.isEmpty || _searchResults.isEmpty) {
      return SelectableText(
        content,
        style: TextStyle(
          fontSize: 16,
          height: 1.6,
          color: Colors.black87,
        ),
      );
    }

    // 高亮显示搜索结果
    return RichText(
      text: _buildHighlightedText(content, searchKeyword),
    );
  }

  TextSpan _buildHighlightedText(String content, String keyword) {
    final List<TextSpan> spans = [];
    final RegExp regex = RegExp(keyword, caseSensitive: false);
    int lastMatchEnd = 0;

    for (final match in regex.allMatches(content)) {
      // 添加匹配前的普通文本
      if (match.start > lastMatchEnd) {
        spans.add(TextSpan(
          text: content.substring(lastMatchEnd, match.start),
          style: TextStyle(fontSize: 16, height: 1.6, color: Colors.black87),
        ));
      }

      // 添加高亮的匹配文本
      spans.add(TextSpan(
        text: match.group(0),
        style: TextStyle(
          fontSize: 16,
          height: 1.6,
          backgroundColor: Colors.yellow[300],
          color: Colors.black87,
          fontWeight: FontWeight.bold,
        ),
      ));

      lastMatchEnd = match.end;
    }

    // 添加最后的普通文本
    if (lastMatchEnd < content.length) {
      spans.add(TextSpan(
        text: content.substring(lastMatchEnd),
        style: TextStyle(fontSize: 16, height: 1.6, color: Colors.black87),
      ));
    }

    return TextSpan(children: spans);
  }
}

/// DOCX文件查看器页面
class DocxViewerPage extends StatelessWidget {
  final String filePath;
  final String? title;

  const DocxViewerPage({
    Key? key,
    required this.filePath,
    this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title ?? 'DOCX文档查看器'),
        actions: [
          IconButton(
            icon: Icon(Icons.info_outline),
            onPressed: () => _showFileInfo(context),
          ),
        ],
      ),
      body: DocxViewerWidget(
        filePath: filePath,
        title: title,
      ),
    );
  }

  void _showFileInfo(BuildContext context) async {
    try {
      final docxReader = DocxReaderService();
      final fileInfo = await docxReader.getDocxFileInfo(filePath);

      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('文件信息'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildInfoRow('文件名', fileInfo.fileName),
              _buildInfoRow('大小', fileInfo.formattedFileSize),
              _buildInfoRow('字数', '${fileInfo.wordCount}'),
              _buildInfoRow('段落数', '${fileInfo.paragraphCount}'),
              _buildInfoRow('修改时间', fileInfo.lastModified.toString()),
              SizedBox(height: 16),
              Text('内容预览:', style: TextStyle(fontWeight: FontWeight.bold)),
              SizedBox(height: 8),
              Container(
                padding: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  fileInfo.contentPreview,
                  style: TextStyle(fontSize: 12),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('关闭'),
            ),
          ],
        ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取文件信息失败: $e')),
      );
    }
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: TextStyle(fontWeight: FontWeight.w500),
            ),
          ),
          Expanded(child: Text(value)),
        ],
      ),
    );
  }
} 